import { JSESSIONIDKey } from "../../const";
import { util } from "utils";
import type { CardInfo } from "../Card.type";
function getCookieFromHeader(headers: { [k: string]: any }): string | undefined {
    if (headers && headers["set-cookie"]) {
        let cookies = headers["set-cookie"];
        if (Array.isArray(cookies) && cookies.length > 0) {
            let cookieMap = {} as { [k: string]: any };
            cookies.forEach((e) => {
                if (typeof e === "string") {
                    let splitArr = e.split(/[;；]/);
                    splitArr.forEach((item) => {
                        let subArr = item.split("=");
                        if (subArr.length === 2) {
                            cookieMap[subArr[0]] = subArr[1];
                        }
                    });
                }
            });
            return cookieMap[JSESSIONIDKey];
        }
    }

    return undefined;
}

// 获取数值
function getNumberValue(o: any): number | null {
    if (util.nilValue(o)) {
        return null;
    }
    if (typeof o === "number") {
        return o;
    }
    if (typeof o === "string") {
        let tmp = o.trim();
        if (tmp.length === 0) {
            return null;
        }
        let num = Number(tmp);
        if (Number.isNaN(num)) {
            return null;
        }
        return num;
    }
    return null;
}

function number2String(num: number): string {
    if (Number.isInteger(num)) {
        return String(num);
    }
    return num.toFixed(2);
}

// 格式化 数据
function formatterData(origin: { [k: string]: any }): CardInfo {
    // 过期时间
    let expireDate = "";
    let next = origin?.nextCardLifeList;
    if (Array.isArray(next) && next.length > 0) {
        expireDate = next[0].nextExpireDateStr ?? "";
    } else {
        expireDate = origin?.entity?.expireDate ?? "";
    }
    // 一共
    let total = "";
    let left = "";
    let totalNumber = getNumberValue(origin?.entity?.flowSize);
    if (!util.nilValue(totalNumber)) {
        total = number2String(totalNumber! / 1024);
        // 计算剩余
        let useNumber = getNumberValue(origin?.entity?.totalBytesCnt);
        if (!util.nilValue(useNumber)) {
            left = number2String((totalNumber! - useNumber!) / 1024);
        }
    }
    return {
        expireDate: expireDate,
        total,
        left,
        status: origin?.entity?.statusStr ?? "未知状态",
    };
}

export { getCookieFromHeader, formatterData };
